package tablet.module_user.activity;

import android.app.AlarmManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.bean.ConfigBean;
import com.lib.bean.UpdateVersionBean;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.permission.custom.PermissionUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.utils.string_deal.regex.RegexUtils;
import com.lib.fastkit.utils.system.SystemUtil;
import com.lib.fastkit.utils.time_deal.TimeUtils;
import com.lib.fastkit.utils.timer_countdown.CountDownTimer;
import com.lib.fastkit.views.dialog.zenhui.AlertDialog;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.utls.appupdate.AppDownloadManager;
import com.lib.utls.appupdate.AppUpdateDialog;
import com.lib.utls.internetime.InterneTimeUtil;
import com.umeng.analytics.MobclickAgent;

import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.OnClick;
import qqkj.qqkj_library.app.install.InstallUtil;
import qqkj.qqkj_library.network.http.HttpDownloadUtil;
import tablet.module_user.R;
import tablet.module_user.R2;
import tablet.module_user.bean.BaseLoginBean;
import tablet.module_user.fragment.XieYiFragment;
import tablet.module_user.util.DeviceIdUtil;

/**
 * Created by Administrator on 2020/7/17 0017.
 */

@Route(path = ARouterPathUtils.Tablet_User_LoginActivity)
public class LoginActivity extends BaseAppActivity {

    @BindView(R2.id.btn_code)
    Button btnCode;
    @BindView(R2.id.btn_login)
    Button btnLogin;
    @BindView(R2.id.tv_xieyi1)
    TextView tvXieyi;

    @BindView(R2.id.et_phone)
    EditText etphone;

    @BindView(R2.id.et_code)
    EditText etCode;

    @BindView(R2.id.checkBox)
    CheckBox checkBox;

    @BindView(R2.id.iv_delete)
    ImageView ivDelete;

    ConfigBean configBean;

    public String flashid = "";

    AppDownloadManager downloadManager;

    @Override
    protected void onCreateView() {

        initPermissionAndUpdate();

//        judgeSystemTime();
    }

    public void initPermissionAndUpdate() {

        initPermission();

        //更新检测，有更新，弹出更新提示框
        chooseUpdateMethod();

    }

    //获取系统时间，并判断时间是否正常
    public void judgeSystemTime() {

        //获取系统时间，并判断时间是否正常，如果不正常，获取网络时间。并修改系统时间
        String sysTime = TimeUtils.getNowString(TimeUtils.FORMAT_6);
        if (StringUtil.isNotEmpty(sysTime, true)) {
            String[] sysYear = sysTime.split("-");
            LogUtil.e("获取到系统时间为：" + sysTime + ",年份为：" + sysYear[0]);

            if (Integer.parseInt(sysYear[0]) > 2018) {

                initPermissionAndUpdate();

            } else {

                String internetTime = VisitURL("http://www.baidu.com");
                LogUtil.e("获取到的网络时间为：" + internetTime);

                if (StringUtil.isNotEmpty(internetTime, true)) {
                    String[] internetStr = internetTime.split("-");
                    final int year, month, day, hour, minute;
                    year = Integer.parseInt(internetStr[0]);
                    month = Integer.parseInt(internetStr[1]);
                    day = Integer.parseInt(internetStr[2]);
                    hour = Integer.parseInt(internetStr[3]);
                    minute = Integer.parseInt(internetStr[4]);

                    PermissionUtil.getInstance(this).externalMain(new PermissionUtil.RequestPermission() {
                        @Override
                        public void onRequestPermissionSuccess() {

                            setSysTime(year, month, day, hour, minute);
                        }

                        @Override
                        public void onRequestPermissionFailure() {

                        }
                    });
                }

                LogUtil.e("修改系统时间之后，获取到的系统时间为：" + TimeUtils.getNowString(TimeUtils.FORMAT_6));

                initPermissionAndUpdate();
            }
        }
    }

    /**
     * 网址访问
     *
     * @param url 网址
     * @return urlDate 对象网址时间
     */
    public static String VisitURL(String url) {
        String urlDate = null;
        try {
            URL url1 = new URL(url);
            URLConnection conn = url1.openConnection();  //生成连接对象
            conn.connect();  //连接对象网页
            Date date = new Date(conn.getDate());  //获取对象网址时间
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm");  //设置日期格式
            urlDate = df.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return urlDate;
    }

    public void setSysTime(int year, int month, int day, int hour, int minute) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, day);
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        long when = c.getTimeInMillis();

        if (when / 1000 < Integer.MAX_VALUE) {
            ((AlarmManager) getSystemService(Context.ALARM_SERVICE)).setTime(when);
        }
    }

    private void initPermission() {

        PermissionUtil.getInstance(this).externalMain(new PermissionUtil.RequestPermission() {
            @Override
            public void onRequestPermissionSuccess() {

            }

            @Override
            public void onRequestPermissionFailure() {

            }

        });

    }

    private void chooseUpdateMethod() {

        showUpdateDialog();
    }

    private void showUpdateDialog() {

        HttpUtils.with(this)
                .addParam("requestType", "TABLET_VERSION")
                .addParam("version_type", "2")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<UpdateVersionBean>() {
                    @Override
                    public void onSuccess(UpdateVersionBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            double localVersion = SystemUtil.getVersionCode(LoginActivity.this);

                            double newVersion = 0;

                            if (!"".equals(result.getObj().getVersion()) || null != result.getObj().getVersion()) {
                                newVersion = Double.parseDouble(result.getObj().getVersion());
                            }

                            if (newVersion > localVersion) {

                                initDialogUI(result);

//                                downloadApk(result);
                            } else {

                                requestConfig();

                                //获取平板的设备Id
                                flashid = DeviceIdUtil.getDeviceId(LoginActivity.this);
                                LogUtil.e("设备的唯一序列号为：" + flashid);
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    public void downloadApk(UpdateVersionBean result) {
        //参数说明1:String(网络请求地址)
        //
        //参数说明2:String(下载文件存放的目录名称,例如存放到手机根目录下/aaa文件夹,则传aaa)
        //
        //参数说明3:String(下载后保存的文件名称, 例如 aaa.jpg,aaa.zip,aaa.xxxx)
        //
        //参数说明4:boolean(是否打开调试日志...设置为true 的时候 logcat中输入 qqkj_frame)
        //
        //参数说明5:HttpDownloadListener(下载进度回调监听,例如,返回10,就是10%)
        //
        //作者：陈二二二狗
        //链接：https://www.jianshu.com/p/357c0717fb1d
        //来源：简书
        //著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

        final String savePath = Environment.getExternalStorageDirectory() + "/xstablet/apkfile/";
        HttpDownloadUtil.getIns().get_http_download(result.getObj().getDownload_url(),
                "xstablet", "xstablet" + result.getObj().getVersion_name() + ".apk",
                true, new HttpDownloadUtil.HttpDownloadListener() {
                    @Override
                    public void get_progress(int i) {
                        if (i == 100) {
                            InstallUtil.getIns(LoginActivity.this)._get_install_apk("xstablet");
                        }
                    }
                });
    }


    private void initDialogUI(final UpdateVersionBean result) {

//        String updateIntroduce = "";
//        if (result.getObj().getVersion_introduction() != null) {
//            for (int i = 0; i < result.getObj().getVersion_introduction().size(); i++) {
//                if (StringUtil.isNotEmpty(result.getObj().getVersion_introduction().get(i), true)) {
//                    updateIntroduce = updateIntroduce + result.getObj().getVersion_introduction().get(i) + "\n";
//                }
//            }
//        }
//
//        UpdateConfig updateConfig = new UpdateConfig();
//        updateConfig.setCheckWifi(true);
//        updateConfig.setNeedCheckMd5(true);
//        updateConfig.setApkSaveName("xstablet.apk");
//        String apkDownloadPath = Environment.getExternalStorageDirectory() + "/xstablet/apkPath/";
//        updateConfig.setApkSavePath(apkDownloadPath);
//        updateConfig.setAlwaysShow(true);//是否强制更新
//        updateConfig.isShowNotification();
//        updateConfig.setShowDownloadingToast(true);
//
//        UiConfig uiConfig = new UiConfig();
//        uiConfig.setUiType(UiType.CUSTOM);
//        uiConfig.setCustomLayoutId(R.layout.dialog_app_update);
//
//        UpdateAppUtils
//                .getInstance()
//                .apkUrl(result.getObj().getDownload_url())
//                .updateTitle("发现新版本" + result.getObj().getVersion_name())
//                .updateContent(updateIntroduce)
//                .updateConfig(updateConfig)
//                .uiConfig(uiConfig)
//                .setOnInitUiListener(new OnInitUiListener() {
//                    @Override
//                    public void onInitUpdateUi(@Nullable View view, @NotNull UpdateConfig updateConfig, @NotNull UiConfig uiConfig) {
//
//                        ImageView imageIcon = view.findViewById(R.id.iv_update_icon);
//                        ImageView imageCancel = view.findViewById(R.id.btn_update_cancel);
//
//                        TextView tvVersion = view.findViewById(R.id.tv_versioncode);
//                        TextView tvDes1 = view.findViewById(R.id.tv_versiontext1);
//                        TextView tvDes2 = view.findViewById(R.id.tv_versiontext2);
//                        TextView tvDes3 = view.findViewById(R.id.tv_versiontext3);
//                        Button btnUpdate = view.findViewById(R.id.btn_update_sure);
//
//                        Glide.with(LoginActivity.this)
//                                .load(result.getObj().getIcon())
//                                .apply(GlideConfig.getRoundOptions(1))
//                                .into(imageIcon);
//
//                        tvVersion.setText("发现新版本" + result.getObj().getVersion_name());
//
//                        List<String> desList = new ArrayList<>();
//                        desList = result.getObj().getVersion_introduction();
//
//                        if (desList.size() == 1) {
//
//                            tvDes1.setText(desList.get(0));
//                            tvDes2.setVisibility(View.INVISIBLE);
//                            tvDes3.setVisibility(View.INVISIBLE);
//
//                        } else if (desList.size() == 2) {
//
//                            tvDes1.setText(desList.get(0));
//                            tvDes2.setText(desList.get(1));
//                            tvDes3.setVisibility(View.INVISIBLE);
//
//                        } else if (desList.size() == 3) {
//
//                            tvDes1.setText(desList.get(0));
//                            tvDes2.setText(desList.get(1));
//                            tvDes3.setText(desList.get(2));
//
//                        }
//
//                    }
//                })
//                .update();

        AppUpdateDialog dialog = new AppUpdateDialog(this);
        dialog.setAppUpdateInfo(result);

        downloadManager = new AppDownloadManager(LoginActivity.this);

        if (downloadManager != null) {
            downloadManager.resume();
        }

        dialog.setOnUpdateClickListener(new AppUpdateDialog.OnUpdateClickListener() {
            @Override
            public void update(final AppUpdateDialog updateDialog) {
                String title = "版本" + result.getObj().getVersion_name();
                String desc = "新版来啦";

                downloadManager.setUpdateListener(new AppDownloadManager.OnUpdateListener() {
                    @Override
                    public void update(int currentByte, int totalByte) {

                        LogUtil.e("------------------------当前的大小为：" + currentByte);
                        LogUtil.e("------------------------总的大小为：" + totalByte);

                    }
                });

                downloadManager.downloadApk(result.getObj().getDownload_url(), title, desc);
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.show();

    }


    private void requestConfig() {

        HttpUtils.with(this)
                .addParam("requestType", "CONFIG")
                .execute(new HttpNormalCallBack<ConfigBean>() {
                    @Override
                    public void onSuccess(ConfigBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            configBean = result;
                            SharedPreferenceManager.getInstance(LoginActivity.this).getUserCache().setQiNiuToken(result.getObj().getToken());
                            SharedPreferenceManager.getInstance(LoginActivity.this).getUserCache().setQiNiuUrl(result.getObj().getBaseurl());
                            SharedPreferenceManager.getInstance(LoginActivity.this).getUserCache().setConfigJson(new Gson().toJson(result));

                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    @Override
    protected void onResume() {

        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }


    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            //bg_circle_gray_border_r10  #989898
            btnCode.setText(millisUntilFinished / 1000 + "秒");
            btnCode.setBackgroundResource(R.drawable.bg_circle_gray_border_r10);
            btnCode.setTextColor(getResources().getColor(R.color.c3));
        }

        @Override
        public void onFinish() {
            btnCode.setEnabled(true);

            btnCode.setBackgroundResource(R.drawable.bg_circle_gradient_r10);
            btnCode.setTextColor(getResources().getColor(tablet.module_user.R.color.white));
            btnCode.setText("获取验证码");

        }
    };


    @OnClick({R2.id.btn_code, R2.id.btn_login, R2.id.tv_xieyi1, R2.id.tv_xieyi2, R2.id.tv_xieyi3, R2.id.iv_delete})
    public void onViewClicked(View view) {
        int i = view.getId();
        UserCacheInterface userCacheInterface;
        if (i == tablet.module_user.R.id.btn_code) {
            requestCode();

        } else if (i == tablet.module_user.R.id.btn_login) {

            if (checkBox.isChecked()) {
                requestLogin();
            } else {
                showToast("请阅读注册协议");
            }


        } else if (i == R.id.tv_xieyi1) {

            //ARouter.getInstance().build(ARouterPathUtils.User_XieyiActivity).navigation();
            if (configBean != null) {
                if (notEmpty(configBean.getObj().getReg_protocol())) {
                    String xieyi1 = configBean.getObj().getReg_protocol();

                    userCacheInterface = SharedPreferenceManager.getInstance(this).getUserCache();
                    userCacheInterface.setXieYiUrl(xieyi1);

                    showXieYi();
                }
            } else {
                requestConfig();
            }


        } else if (i == tablet.module_user.R.id.tv_xieyi2) {

            //ARouter.getInstance().build(ARouterPathUtils.User_XieyiActivity).navigation();
            if (configBean != null) {
                if (notEmpty(configBean.getObj().getPrivacy_policy_protocol())) {
                    String xieyi2 = configBean.getObj().getPrivacy_policy_protocol();

                    userCacheInterface = SharedPreferenceManager.getInstance(this).getUserCache();
                    userCacheInterface.setXieYiUrl(xieyi2);

                    showXieYi();
                }
            } else {
                requestConfig();
            }


        } else if (i == tablet.module_user.R.id.tv_xieyi3) {

            //ARouter.getInstance().build(ARouterPathUtils.User_XieyiActivity).navigation();
            if (configBean != null) {
            if (notEmpty(configBean.getObj().getCommitment_statement_protocol())) {
                String xieyi3 = configBean.getObj().getCommitment_statement_protocol();

                userCacheInterface = SharedPreferenceManager.getInstance(this).getUserCache();
                userCacheInterface.setXieYiUrl(xieyi3);

                showXieYi();
            }
            } else {
                requestConfig();
            }

        } else if (i == tablet.module_user.R.id.iv_delete) {

            etphone.setText("");
        }
    }

    private void requestLogin() {
        String phone = etphone.getText().toString().trim();
        String code = etCode.getText().toString().trim();

        if (!RegexUtils.checkCode(this, code)) {

            return;
        }


        if (!RegexUtils.checkPhone(this, phone)) {

            return;
        }

        HttpUtils.with(this)
                .addParam("requestType", "TABLET_LOGIN")
                .addParam("phone", phone)
                .addParam("code", code)
                .addParam("device_code", flashid)
                .execute(new HttpDialogCallBack<BaseLoginBean>() {
                    @Override
                    public void onSuccess(BaseLoginBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            LogUtil.e("登录成功！");

                            UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(LoginActivity.this).getUserCache();
                            userCacheInterface.setUserName(result.getObj().getName());
                            userCacheInterface.setUserToken(result.getObj().getToken());
                            userCacheInterface.setUserIdentity(result.getObj().getIdentity() + "");
                            userCacheInterface.setUserHeadUrl(result.getObj().getPhoto_url());
                            userCacheInterface.setUserPhone(result.getObj().getPhone());
                            userCacheInterface.setIsLogin(true);
                            //保存是否为平台老师
                            userCacheInterface.setPlatform_teacher(result.getObj().getPlatform_teacher());

                            //是否是第一次登陆，0-是，1-不是-------是否购买套餐，0-没有购买，1-已购买
                            //需要将套餐数据传递到首页去显示

                            LogUtil.e("First_login的值为：" + result.getObj().getFirst_login());

                            String package_content = "";
                            if (result.getObj().getFirst_login() == 0 && result.getObj().getWhether_to_buy() == 1) {

                                package_content = MGson.newGson().toJson(result.getObj().getPackage_content());
                                LogUtil.e("用户的套餐数据为：" + package_content);
                            }
                            if (StringUtil.isNotEmpty(package_content, true)) {

                                LogUtil.e("package_content的值不为空");
                                ARouter.getInstance().build(ARouterPathUtils.Tablet_App_MainActivity)
                                        .withString("package_content", package_content)
                                        .navigation();
                            } else {

                                LogUtil.e("package_content的值为空");
                                ARouter.getInstance().build(ARouterPathUtils.Tablet_App_MainActivity)
                                        .navigation();
                            }

//                            EventBus.getDefault().post(new Event<>(1, "登录成功"), EventBusTagUtils.LoginActivity);

                            //登录成功之后将用户的电话作为id绑定到友盟用户统计中
                            MobclickAgent.onProfileSignIn(result.getObj().getPhone());
                            showToast(result.getMsg());

                            finish();

                        } else if (result.getCode() == CodeUtil.CODE_402) {

                            new Thread(new Runnable() {
                                @Override
                                public void run() {

                                    try {
                                        Thread.sleep(500);
                                        requestCheckCode();
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();

                        } else {

                            showToast(result.getMsg());
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    /**
     * 检测验证码
     */
    private void requestCheckCode() {
        String phone = etphone.getText().toString().trim();
        String code = etCode.getText().toString().trim();

        UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(LoginActivity.this).getUserCache();
        userCacheInterface.setUserPhone(phone);

        if (!RegexUtils.checkCode(this, code)) {

            return;
        }


        if (!RegexUtils.checkPhone(this, phone)) {

            return;
        }

        LogUtil.e("开始请求");

        HttpUtils.with(this)
                .addParam("requestType", "VERIFY_CODE_CHECK")
                .addParam("phone", phone)
                .addParam("code", code)
                .execute(new HttpNormalCallBack<BaseLoginBean>() {
                    @Override
                    public void onSuccess(BaseLoginBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            ARouter.getInstance().build(ARouterPathUtils.Tablet_User_IdentityActivity).navigation();

                        }
                        showToast(result.getMsg());
                    }

                    @Override
                    public void onError(String e) {
                        LogUtil.e(e);
                    }
                });


    }

    private void requestCode() {
        String phone = etphone.getText().toString().trim();
        if (!RegexUtils.checkPhone(this, phone)) {

            return;
        }
        HttpUtils.with(this)
                .addParam("requestType", "VERIFY_CODE_SEND")
                .addParam("phone", phone)
                .execute(new HttpNormalCallBack<BaseLoginBean>() {
                    @Override
                    public void onSuccess(BaseLoginBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {
                            btnCode.setEnabled(false);
                            btnCode.setBackgroundResource(tablet.module_user.R.drawable.bg_circle_hollow_r10);
                            btnCode.setTextColor(getResources().getColor(tablet.module_user.R.color.base_text1));
                            timer.start();
                        }
                        showToast(result.getMsg());

                    }

                    @Override
                    public void onError(String e) {

                    }
                });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }


    XieYiFragment xieYiFragment;

    private void showXieYi() {

        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setContentView(R.layout.dialog_xieyi)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (xieYiFragment != null) {
                            getSupportFragmentManager().beginTransaction().remove(xieYiFragment).commit();
                            xieYiFragment = null;
                        }
                    }
                })
                .fullWidth()
                .addDefaultAnimation()
                .show();

        xieYiFragment = (XieYiFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_xieyi);
    }


    public boolean notEmpty(String str) {

        if ("".equals(str) && null != str && "null".equals(str)) {
            return false;
        }
        return true;
    }
}
